<template>
  <div class="about">
    <a-upload
      :multiple="true"
      :file-list="fileList"
      :customRequest="() => {}"
      :before-upload="beforeUpload"
      @change="handleChange"
    >
      <a-button>
        <upload-outlined></upload-outlined>
        上传
      </a-button>
    </a-upload>
    <a-row>
      <a-col :span="6" v-for="(item, idx) of imageUrls" :key="idx">
        <a-image
          :width="300"
          :height="200"
          :style="{
            backgroundColor: randomRGB()
          }"
          :src="item.url"
        />
        <p>{{ item.text }}</p>
      </a-col>
    </a-row>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import type { UploadChangeParam, UploadProps } from 'ant-design-vue'
import { UploadOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { getCOSClient } from '@/utils/sys'
interface imageProps {
  url: string
  text: string
}
const imageUrls = ref<imageProps[]>([])
const fileList = ref([])
const contents = ref<string[]>([])
const loading = ref<boolean>(false)
const COSConfig = {
  Bucket: 'sls-cloudfunction-ap-guangzhou-code-1258416275' /* 必须 */,
  Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */
}

onMounted(() => {
  getCOSImg()
})

const getCOSImg = async () => {
  const cos = await getCOSClient()
  cos.getBucket(
    {
      ...COSConfig,
      Prefix: 'images/'
    },
    function (err, data) {
      if (data.Contents) {
        contents.value = data.Contents.map((item) => item.Key)
        getOSSUrl()
      }
      if (err) message.error(err.toString())
    }
  )
}

const getOSSUrl = async () => {
  const cos = await getCOSClient()
  for (let item of contents.value) {
    cos.getObjectUrl(
      {
        ...COSConfig,
        Key: item,
        Sign: true
      },
      function (err, data) {
        if (data.Url) {
          imageUrls.value = [
            ...imageUrls.value,
            {
              url: data.Url,
              text: item
            }
          ]
        }
        if (err) message.error(err.toString())
      }
    )
  }
}

async function putFile(name, fileObject) {
  const cos = await getCOSClient()
  cos.putObject(
    {
      ...COSConfig,
      Key: name,
      StorageClass: 'STANDARD',
      Body: fileObject, // 上传文件对象
      onProgress: function (progressData) {
        console.log(JSON.stringify(progressData))
      }
    },
    function (err, data) {
      if (data) {
        message.success('上传成功')
        console.log(data)
        imageUrls.value = []
        getCOSImg()
      }
      if (err) message.error(err.toString())
    }
  )
}

const deleteFile = async (name) => {
  const cos = await getCOSClient()
  Modal.confirm({
    title: '确定要删除吗？',
    okText: '是的',
    okType: 'danger',
    cancelText: '返回',
    onOk() {
      cos.deleteObject(
        {
          ...COSConfig,
          Key: name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        },
        function (err, data) {
          if (data) {
            message.success('删除成功')
          }
          if (err) message.error(err.toString())
        }
      )
    }
  })
}

const handleChange = (info: UploadChangeParam) => {
  putFile('images/' + info.file.name, info.file.originFileObj)
}
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传JPG，PNG文件!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片不能大于2MB!')
  }
  return isJpgOrPng && isLt2M
}

/**
 * 生成随机色值
 */
const randomRGB = () => {
  const r = Math.floor(Math.random() * 255)
  const g = Math.floor(Math.random() * 255)
  const b = Math.floor(Math.random() * 255)
  return `rgb(${r}, ${g}, ${b})`
}
</script>

<style lang="scss" scoped>
.about {
  max-height: calc(100vh - 83px);
  overflow-y: scroll;
  &::-webkit-scrollbar-thumb {
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    -ms-border-radius: 10px;
    border-radius: 10px;
    background-color: #c2c2c2;
  }
  /*定义滚动条轨道 内阴影+圆角*/
  &::-webkit-scrollbar-track {
    border-radius: 10px;
  }
  /*定义滚动条高宽及背景*/
  &::-webkit-scrollbar {
    width: 10px;
  }
  .ant-col {
    margin-top: 20px;
    p {
      margin-top: 10px;
      font-size: 14px;
      font-weight: 700;
      font-family: ui-sans-serif, system-ui, -apple-system;
    }
    ::v-deep .ant-image {
      border-radius: 10px;
      box-shadow: 5px 5px 3px #888888;
      overflow: hidden;
      img{
        background-repeat: no-repeat;
        background-size: cover;
      }
    }
    ::v-deep .ant-image-mask {
      border-radius: 10px;
    }
  }
}
</style>
